package com.eastmoney.emis.edda.task.report;


import com.eastmoney.emis.edda.domain.entity.EddaApply;
import com.eastmoney.emis.edda.domain.entity.EddaBind;
import com.eastmoney.emis.edda.domain.event.EddaAuthEnquiryEvent;
import com.eastmoney.emis.edda.domain.event.EventPublisher;
import com.eastmoney.emis.edda.domain.repository.HsbcEddaRepository;
import com.eastmoney.emis.edda.domain.valueobject.EddaApplyStatus;
import com.eastmoney.emis.edda.infrastructure.report.DDAReport;
import com.eastmoney.emis.edda.infrastructure.report.DDAReportRecord;
import com.eastmoney.emis.logger.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DDAReportEventHandler {

    private static final Logger log = LoggerFactory.getLogger(DDAReportEventHandler.class);

    @Autowired
    private HsbcEddaRepository hsbcEddaRepository;
    @Autowired
    private EventPublisher eventPublisher;

    @Async("eddaTaskExecutor")
    @EventListener
    public void processDDAReportRecord(DDAReport ddaReport) {
        List<DDAReportRecord> reportRecords = ddaReport.getReportRecords();
        if (reportRecords == null || reportRecords.isEmpty()) {
            return;
        }

        for (DDAReportRecord reportRecord : reportRecords) {
            EddaApply eddaApply = hsbcEddaRepository.findEddaApplyByClientIdAndRegisterId(
                    reportRecord.getCreditorReference(), reportRecord.getMerchantRequestIdentification());
            if (eddaApply == null) {
                log.warn("not found edda apply but report exists, {}", reportRecord);
                continue;
            }
            if (eddaApply.fail()) {
                continue;
            }
            eddaApply.status(EddaApplyStatus.FAIL);
            hsbcEddaRepository.save(eddaApply);

            EddaAuthEnquiryEvent event = new EddaAuthEnquiryEvent(eddaApply);
            event.setResult(reportRecord.getRejectReasonInformation());
            event.setProcessUserName("system-report");
            eventPublisher.publish(event);
            // 更新 bind
            EddaBind eddaBind = hsbcEddaRepository.findEddaBindByClientIdAndBankAccount(
                    eddaApply.getClientId(), eddaApply.getBankCode(), eddaApply.getBankAccount());
            if (eddaBind == null) {
                continue;
            }
            if (eddaBind.finished() && !eddaBind.getRegisterId().equals(eddaApply.getRegisterId())) {
                continue;
            }
            eddaBind.fail(eddaApply);
            hsbcEddaRepository.save(eddaBind);
        }

    }
}
